<script setup lang="ts">
  import { FormInstance } from 'element-plus'
  import { PropType, onMounted, ref, watch } from 'vue'
  import {
    useNetworkOptions,
    useAssignNetworkForm,
    useNetworkTypeOptions,
    useServicePersonalOptions,
  } from './services'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { useRouter } from 'vue-router'
  import { NetowrkOptional } from './services/types'

  const {
    servicePersonalOptions,
    getServicePersonalOptionsLoading,
    getServicePersonalOptions,
    clearServicePersonalOptions,
  } = useServicePersonalOptions()
  const { networkOptions, getNetworkOptions, getNetworkOptionsLoading } = useNetworkOptions()
  const { networkTypeOptions, getNetworkTypeOptionsLoading, getNetworkTypeOptions } =
    useNetworkTypeOptions()
  const { formData, submitLoading, reset, submit } = useAssignNetworkForm()

  const props = defineProps({
    address: {
      type: Object as PropType<{
        province: string
        city: string
        area: string
        town: string
      }>,
      default: () => {
        return {
          province: '',
          city: '',
          area: '',
          town: '',
        }
      },
    },
    networkId: String,
  })

  const emits = defineEmits<{
    (e: 'addNetwork'): void
  }>()

  // 全局路由对象
  const router = useRouter()

  const networkType = ref('')
  const serviceScope = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const formRef = ref<FormInstance | null>(null)
  const rules = ref({
    networkId: [{ required: true, message: '请选择部门！', trigger: ['blur', 'change'] }],
  })
  const areaType = ref(1)
  /**
   * 查询条件
   * 0 - 全部
   * 1 - 按部门分类
   * 2 - 服务区域
   * 3 - 公司地址
   */
  const queryCondition = ref(0)
  const selectedNetwork = ref<NetowrkOptional>({
    autoSureReceiveOrder: false,
    category: 0,
    id: '',
    name: '',
    select: false,
    teamType: 0,
  })

  const onQueryConditionChange = () => {
    if (queryCondition.value === 1) {
      networkType.value = '0'
      getNetworkTypeOptions('')
    }
    formRef.value && formRef.value.resetFields()
    formData.value.networkEmpId = ''
    clearServicePersonalOptions()
    if ([3, 2].includes(queryCondition.value)) {
      if (props.address.province && props.address.city && props.address.area) {
        Object.assign(serviceScope.value, props.address)
      }
    }
    getNetworkOptionsKeyword.value = ''
    getNetworkTypeOptionsKeyword.value = ''
    getServicePersonalOptionsKeyword.value = ''
    callGetNetworkOptions()
  }

  const onAddressChange = (address: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    serviceScope.value.province = address.province
    serviceScope.value.city = address.city
    serviceScope.value.area = address.area
    serviceScope.value.town = address.town
    callGetNetworkOptions()
  }

  const getNetworkTypeOptionsKeyword = ref('')
  const callGetNetworkTypeOptions = () => {
    getNetworkTypeOptions(getNetworkTypeOptionsKeyword.value)
  }

  const onNetworkTypeChange = () => {
    formData.value.networkId = ''
    formData.value.networkEmpId = ''
    getNetworkOptionsKeyword.value = ''
    getServicePersonalOptionsKeyword.value = ''
    clearServicePersonalOptions()
    callGetNetworkOptions()
  }

  const getNetworkOptionsKeyword = ref('')
  const callGetNetworkOptions = () => {
    getNetworkOptions({
      province: serviceScope.value.province,
      area: serviceScope.value.area,
      city: serviceScope.value.city,
      queryCondition: queryCondition.value,
      keyword: getNetworkOptionsKeyword.value,
      networkType: networkType.value,
      areaType: areaType.value,
    })
  }

  const onNetworkChange = () => {
    formData.value.networkEmpId = ''
    getServicePersonalOptionsKeyword.value = ''
    getServicePersonalOptions('', formData.value.networkId)
    const network = networkOptions.value.find((item) => item.id === formData.value.networkId)
    if (network) {
      selectedNetwork.value = network
    }
  }

  const getServicePersonalOptionsKeyword = ref('')
  const callGetServicePersonOptions = () => {
    getServicePersonalOptions(getServicePersonalOptionsKeyword.value, formData.value.networkId)
  }

  const save = async (workIds: Array<string>) => {
    if (formRef.value) {
      try {
        await formRef.value.validate()
        return await submit(workIds)
      } catch (error) {
        throw new Error('表单验证失败')
      }
    }
  }

  const _reset = () => {
    networkType.value = ''
    queryCondition.value = 0
    serviceScope.value = {
      city: '',
      area: '',
      province: '',
      town: '',
    }
    reset()
  }

  /**
   * 添加部门
   */
  const onAddNetwork = () => {
    emits('addNetwork')
    router.push({ path: '/net/new' })
    // if (queryCondition.value === 1) {
    //   router.push({ path: '/net/new', query: { networkType: networkType.value } })
    // }

    // if ([2, 3].includes(queryCondition.value)) {
    //   router.push({ path: '/net/new', query: { address: JSON.stringify(serviceScope.value) } })
    // }
  }

  watch(
    props,
    (value) => {
      serviceScope.value.province = value.address.province || ''
      serviceScope.value.city = value.address.city || ''
      serviceScope.value.area = value.address.area || ''
      serviceScope.value.town = value.address.town || ''
      areaType.value = 1
      queryCondition.value = 0
      servicePersonalOptions.value = []
      onQueryConditionChange()
    },
    { immediate: true, deep: true },
  )

  onMounted(() => {
    callGetNetworkOptions()
  })

  defineExpose({
    saveLoading: submitLoading,
    save,
    resetForm: _reset,
  })
</script>

<template>
  <el-form
    ref="formRef"
    class="modal_form_content"
    label-position="top"
    :model="formData"
    :rules="rules"
    inline-message
  >
    <!-- 查询条件 -->
    <el-form-item label="查询条件">
      <el-select
        v-model="queryCondition"
        placeholder="请选择查询条件"
        filterable
        @change="onQueryConditionChange"
      >
        <el-option :value="0" label="全部" />
        <el-option :value="1" label="部门分类查询" />
        <el-option :value="2" label="部门区域查询" />
        <el-option :value="3" label="公司地址查询" />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="queryCondition == 2 || queryCondition == 3"
      label="地址匹配"
      class="form_select_item"
    >
      <el-select
        v-model="areaType"
        placeholder="请选择查询条件"
        @blur.stop="() => {}"
        @change="onQueryConditionChange"
      >
        <el-option :value="1" label="全地址匹配" />
        <el-option :value="2" label="仅匹配省、市" />
      </el-select>
    </el-form-item>
    <!-- 公司地址 -->
    <el-form-item
      v-show="queryCondition === 3 || queryCondition === 2"
      :label="queryCondition === 3 ? '公司地址' : '部门区域'"
    >
      <SingleAddress clear :address="serviceScope" @change="onAddressChange" />
    </el-form-item>

    <!-- 部门分类 -->
    <el-form-item v-if="queryCondition === 1" label="部门分类">
      <el-select
        v-model="networkType"
        placeholder="部门分类"
        :loading="getNetworkTypeOptionsLoading"
        @change="onNetworkTypeChange"
      >
        <template #header>
          <div class="select_header">
            <el-input
              v-model.trim="getNetworkTypeOptionsKeyword"
              placeholder="请输入关键字"
              @keyup.enter="callGetNetworkTypeOptions"
            />
            <HPlainButton @click="callGetNetworkTypeOptions">搜索</HPlainButton>
          </div>
        </template>
        <el-option value="0" label="全部" />
        <el-option
          v-for="item in networkTypeOptions"
          :key="item.name"
          :disabled="props.networkId === item.id"
          :value="item.id"
          :label="item.name"
        />
      </el-select>
    </el-form-item>

    <!-- 分配部门 -->
    <el-form-item label="分配部门" prop="networkId">
      <el-select
        v-model="formData.networkId"
        placeholder="分配部门"
        :loading="getNetworkOptionsLoading"
        @change="onNetworkChange"
      >
        <template #header>
          <div class="select_header">
            <el-input
              v-model.trim="getNetworkOptionsKeyword"
              placeholder="请输入关键字"
              @keyup.enter="callGetNetworkOptions"
            />
            <HPlainButton @click="callGetNetworkOptions">搜索</HPlainButton>
          </div>
        </template>
        <template #empty>
          <div class="network_empty_container">
            <el-icon color="#e69103" size="20">
              <WarningFilled />
            </el-icon>
            <span v-if="queryCondition === 1">该分类没有相关的服务部门，请前往:</span>
            <span v-if="[2, 3].includes(queryCondition)">该区域没有相关的服务部门，请前往:</span>
            <h-link @click="onAddNetwork">添加部门</h-link>
          </div>
        </template>
        <el-option
          v-for="(item, index) in networkOptions"
          :key="index"
          :disabled="props.networkId === item.id"
          :value="item.id"
          :label="item.name"
        />
      </el-select>
    </el-form-item>

    <!-- 分配人员 -->
    <el-form-item label="分配人员">
      <el-select
        v-model="formData.networkEmpId"
        placeholder="分配人员"
        :loading="getServicePersonalOptionsLoading"
        :disabled="!!selectedNetwork.id && !selectedNetwork.autoSureReceiveOrder"
      >
        <template #header>
          <div class="select_header">
            <el-input
              v-model.trim="getServicePersonalOptionsKeyword"
              placeholder="请输入关键字"
              @keyup.enter="callGetServicePersonOptions"
            />
            <h-plain-button @click="callGetServicePersonOptions">搜索</h-plain-button>
          </div>
        </template>
        <el-option
          v-for="item in servicePersonalOptions"
          :key="item.name"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <!-- 分派备注 -->
    <el-form-item label="分派备注">
      <el-input
        v-model.trim="formData.remark"
        placeholder="请输入分派备注"
        show-word-limit
        type="textarea"
        resize="both"
        maxlength="200"
      />
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
  :deep(.el-textarea) {
    .el-textarea__inner {
      min-height: 75px !important;
      min-width: 100% !important;
      max-width: 400px !important;
      max-height: 120px !important;
    }
  }

  .select_header {
    display: flex;
    gap: 3px;
  }

  .network_empty_container {
    display: flex;
    justify-content: center;
    column-gap: 5px;
    height: 20px;
    line-height: 20px;

    span {
      color: #606266;
      font-size: 12px;
    }
  }
</style>
